/**
 * 简化显示数据用的
 * @huhaiqin
 */
layui.define(['layer', 'jquery', 'laypage', 'laytpl', 'form'], function(exports) {

    var $ = layui.jquery,
        layer = layui.layer,
        laytpl = layui.laytpl,
        laypage = layui.laypage,
        form = layui.form;


    //遍历页面中的datashow
    $('.datashow').each(function() {
        loadSingleDataShow($(this));
    });

    function reflashloaddata() {
        //遍历页面中的datashow
        $('.datashow').each(function() {
            loadSingleDataShow($(this));
        });
    }

    /**
     * 显示一个datashow
     */
    function loadSingleDataShow($datashow, callback) {
        var $loading = $datashow.find('.loading');
        if ($loading.length == 0) {
            $datashow.append('<span class="loading"></span>');
            $loading = $datashow.find('.loading');
        }

        var dataUrl = $datashow.attr('data-url');
        var dataTpl = $datashow.find('script.data-tpl').html();
        var $dataDom = $datashow.find('.data');
        var $pageDom = $datashow.find('.page');
        var p = $datashow.attr('data-p');
        var row = $datashow.attr('data-row');
        var isload = $datashow.attr('data-loading');
        var condition = $datashow.attr('data-condition');
        var fc = $datashow.attr('data-function');
        

        loadData($datashow, dataUrl, dataTpl, $loading, $dataDom, $pageDom, condition, p, row, isload, callback,fc);

    }


    /**
     * 执行请求
     */
    function loadData($datashow, dataUrl, dataTpl, $loading, $dataDom, $pageDom, condition, p, row, isload, callback,fc) {
        if (!dataUrl) {
            layer.alert('数据渲染时，缺少获取数据的地址！');
            return false;
        }
        if (!dataTpl) {
            layer.alert('数据渲染时，缺少模板！')
            return false;
        }
        if (!p) {
            p = 1; //默认当前是第一页
        }
        if (!row) {
            row = 10; //默认一页显示10条记录
        }

        var ii;
        var myCondition = "p=" + p + "&row=" + row;
        if (condition) {
            myCondition = condition + "&" + myCondition;
        }
        $.ajax({
            url: dataUrl,
            cache: true, //缓存数据
            type: "POST",
            data: myCondition,
            dataType: "json",
            beforeSend: function() {
                if (isload != '0') {
                    ii = layer.msg('Loading...', { icon: 16, time: 10000 });
                }
            },
            complete: function() {
                layer.close(ii);
            },
            success: function(res) {
                if (res.status) {
                    //开始渲染数据
                    laytpl(dataTpl).render(res.data.data, function(html) {
                        $dataDom.html(html);
                        //描红关键词begin
                        var toRedStr = $datashow.attr('data-to-red');
                        if (toRedStr != "" && typeof(toRedStr) != "undefined") {
                            var arr = toRedStr.split(":");

                            if (arr.length == 2) {
                                var $redTbs = $datashow.find('.' + arr[0]);
                                //描红
                                $redTbs.each(function() {
                                    var $this = $(this);
                                    $this.html(replace_str_all($this.html(), arr[1], '<span style="color:red;">' + arr[1] + '</span>'));
                                });


                            }
                        }
                        form.render(); //重新渲染表单
                        //描红关键词end
                        listen_ajax_click(); //监听一些操作
                        listen_checkbox_selectall(); //监听全选操作
                        //执行回调函数
                        if (typeof callback == 'function') {
                            callback();
                        }

                    });
                    //载入分页
                    // if ($pageDom.length != 0) {
                    if (res.data.page.total / res.data.page.row > 1) { //当有两页的时候渲染
                        laypage.render({
                            elem: $pageDom,
                            count: res.data.page.total,
                            limit: res.data.page.row,
                            first: 1,
                            //last: Math.ceil(res.data.page.total / res.data.page.row),
                            curr: res.data.page.cur,
                            prev: '上一页',
                            next: '下一页',
                            layout: ['prev', 'page', 'next', 'skip', 'count'],
                            jump: function(obj) {
                                //处理跳转，回调自己（递归）
                                //alert(obj.curr);
                                if (obj.curr != p) {
                                    p = obj.curr;
                                    //当前页发生改变的时候执行一下改变
                                    $datashow.attr('data-p', p);
                                    $datashow.attr('data-row', row);
                                    loadData($datashow, dataUrl, dataTpl, $loading, $dataDom, $pageDom, condition, p, row,'','',fc);
                                    //滚动到顶部
                                    window.scrollTo(0, $dataDom.offset().top);
                                }

                            }
                        });
                    } else {
                        $pageDom.html('');
                    }

                    if(fc){
                        var l = 0;
                        if(res.data.data){
                            l = res.data.data.length;
                        }
                        eval(fc+"("+l+")");
                    }

                } else {
                    layer.msg(res.info, { icon: 2, time: 1000 });
                }
            }
        });
    }

    var datashow = function($datashow, callback) {
        loadSingleDataShow($datashow, callback);
    }


    /**
     * 监听全选
     */
    listen_checkbox_selectall();

    function listen_checkbox_selectall() {
        //全选
        form.on('checkbox(allChoose)', function(data) {
            var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]');
            child.each(function(index, item) {
                item.checked = data.elem.checked;
            });
            form.render('checkbox');
        });
    }


    /**
     * 字符串替代
     */
    function replace_str_all(str, oldStr, newStr) {
        var reg = new RegExp(oldStr, "g");
        str = str.replace(reg, newStr);
        console.log(str);
        return str;
    }
    /**
     * 监听一些ajax操作
     */
    listen_ajax_click();

    function listen_ajax_click() {
        //表单提交
        form.on('submit(*)', function(data) {
            var action = $(data.form).attr('action'),
                button = $(data.elem);
            var $form = $(data.form);
            if ($form.hasClass('submit-holder')) {
                return; //禁止提交，防止重复提交
            }
            var ii;
            $.ajax({
                url: action,
                data: data.field,
                type: "POST",
                dataType: "json",
                beforeSend: function() {
                    $form.addClass('submit-holder'); //防止重复提交
                    ii = layer.msg('Loading...', { icon: 16, time: 10000 });
                },
                complete: function() {
                    layer.close(ii);
                    $form.removeClass('submit-holder'); //解除禁止提交
                },
                success: function(data) {
                    //data = JSON.parse(data);  //str 转 json
                    if (data.status == 1) {
                        layer.msg(data.info, { icon: 1, time: 1000 });
                        //如果有URL参数，先执行URL
                        if (data.url) {
                            setTimeout(function() {
                                location.href = data.url;
                            }, 900);
                        }
                        //关闭父窗口
                        if ($form.hasClass('close-dialog')) {
                            setTimeout(function() {
                                //如果有callback样式，表示成功后要执行回调
                                if ($form.hasClass('callback')) {
                                    parent.mini_callback(data.data); //传一个参数进去
                                }
                                parent.close_iframe_dialog();

                            }, 1000);
                        } else {

                            if ($form.hasClass('callback')) {
                                parent.mini_callback();
                            }

                            if ($form.hasClass('shuaxin')) {
                                setTimeout(function() {
                                    location.reload(); //刷新
                                }, 1000);
                            }
                        }
                    } else {
                        layer.msg(data.info, { icon: 2, time: 1000 });
                    }
                    //需要跳转的话
                    if (data.url) {
                        setTimeout(function() {
                            location.href = data.url;
                        }, 1000);
                    }

                }
            });
            return false;
        });
        //删除操作
        $('.mini_del').click(function() {

            var $this = $(this);
            var asker = layer.confirm('确定删除吗？', function() {
                var ii;
                $.ajax({
                    url: $this.attr('data-url'),
                    type: "get",
                    dataType: "json",
                    beforeSend: function() {
                        ii = layer.msg('Loading...', { icon: 16, time: 10000 });
                    },
                    complete: function() {
                        layer.close(ii);
                    },
                    success: function(data) {
                        if (data.status) {
                            layer.msg('删除成功', { icon: 1, time: 1000 }, function() {
                                if ($this.hasClass('reload')) {
                                    location.reload(); //自动关闭后可做一些刷新页面等操作
                                } else {
                                    reflashloaddata(); //ajax刷新
                                }

                            });
                        } else {
                            layer.msg(data.info, { icon: 2, time: 1000 });
                        }
                    }
                });
            });
        });

        $('.ajax-post').click(function() {
            var $this = $(this);
            var target_form = $(this).attr('target-form');
            var form = $('.' + target_form);
            var query = form.serialize();
            var msg = $this.attr('data-msg');
            if (!query) {
                layer.alert('没有可操作的数据', { icon: 7 });
                return false;
            }

            if (!msg) {
                msg = '确定删除吗？';
            }


            if ($this.hasClass('confirm')) {
                var asker = layer.confirm(msg, function() {

                    var ii = layer.msg('数据处理中...', { icon: 16, time: 10000 });

                    $.post($this.attr('data-url'), query, function(data) {
                        layer.close(ii);
                        if (data.status) {
                            layer.msg(data.info, { icon: 1, time: 1000 });
                            //关闭父窗口
                            if ($this.hasClass('close-dialog')) {
                                setTimeout(function() {
                                    parent.close_iframe_dialog();
                                }, 1000);
                            }
                            if ($this.hasClass('shuaxin')) {
                                setTimeout(function() {
                                    location = location;
                                }, 1000);
                            }
                            if ($this.hasClass('refresh-datashow')) {
                                setTimeout(function() {
                                    reflashloaddata(); //刷新datashow
                                }, 1000);
                            }
                        } else {
                            layer.msg(data.info, { icon: 2, time: 1000 });
                        }

                        //需要跳转的话
                        if (data.info != 'You do not have this authority') {
                            if (data.url) {
                                setTimeout(function() {
                                    location.href = data.url;
                                }, 1000);
                            }
                        }

                    }, 'json');
                });

            } else {
                var ii = layer.msg('数据处理中...', { icon: 16, time: 10000 });

                $.post($this.attr('data-url'), query, function(data) {
                    layer.close(ii);
                    if (data.status) {
                        layer.msg(data.info, { icon: 1, time: 1000 });
                        //关闭父窗口
                        if ($this.hasClass('close-dialog')) {
                            setTimeout(function() {
                                parent.close_iframe_dialog();
                            }, 1000);
                        }

                        if ($this.hasClass('shuaxin')) {
                            setTimeout(function() {
                                location = location;
                            }, 1000);
                        }
                        if ($this.hasClass('refresh-datashow')) {
                            setTimeout(function() {
                                reflashloaddata(); //刷新datashow
                            }, 1000);
                        }
                    } else {
                        layer.msg(data.info, { icon: 2, time: 1000 });
                    }

                    //需要跳转的话
                    if (data.info != 'You do not have this authority') {
                        if (data.url) {
                            setTimeout(function() {
                                location.href = data.url;
                            }, 1000);
                        }
                    }
                }, 'json');

            }
            return false;

        });

        $('.ajax-get').click(function() {
            var $this = $(this);
            var msg = $(this).attr('data-msg');
            if (!msg) {
                msg = '确定删除吗？';
            }
            if ($this.hasClass('confirm')) {
                var asker = layer.confirm(msg, function() {
                    var ii = layer.msg('数据处理中...', { icon: 16, time: 10000 });
                    $.get($this.attr('data-url'), function(data) {
                        layer.close(ii);
                        if (data.status) {
                            layer.msg(data.info, { icon: 1, time: 1000 });
                            //关闭父窗口
                            if ($this.hasClass('close-dialog')) {
                                setTimeout(function() {
                                    parent.close_iframe_dialog();
                                }, 1000);
                            }
                            //刷新父窗口
                            if ($this.hasClass('parent-refresh')) {
                                setTimeout(function() {
                                    parent.refresh();
                                }, 1000);
                            }
                            if ($this.hasClass('shuaxin')) {
                                setTimeout(function() {
                                    location.reload(); //当前页面是否需要刷新
                                }, 1000);
                            }
                            if ($this.hasClass('refresh-datashow')) {
                                setTimeout(function() {
                                    reflashloaddata(); //刷新datashow
                                }, 1000);
                            }
                        } else {
                            layer.msg(data.info, { icon: 2, time: 1000 });
                        }

                        //需要跳转的话
                        if (data.info != 'You do not have this authority') {
                            if (data.url) {
                                setTimeout(function() {
                                    location.href = data.url;
                                }, 1000);
                            }
                        }

                    }, 'json');
                });
            } else {
                var ii = layer.msg('数据处理中...', { icon: 16, time: 10000 });
                $.get($this.attr('data-url'), function(data) {
                    layer.close(ii);
                    if (data.status) {
                        layer.msg(data.info, { icon: 1, time: 1000 });
                        //关闭父窗口
                        if ($this.hasClass('close-dialog')) {
                            setTimeout(function() {
                                parent.close_iframe_dialog();
                            }, 1000);
                        }
                        if ($this.hasClass('shuaxin')) {
                            setTimeout(function() {
                                location.reload(); //当前页面是否需要刷新
                            }, 1000);
                        }
                        if ($this.hasClass('refresh-datashow')) {
                            setTimeout(function() {
                                reflashloaddata(); //刷新datashow
                            }, 1000);
                        }
                    } else {
                        layer.msg(data.info, { icon: 2, time: 1000 });
                    }
                    //需要跳转的话
                    if (data.info != 'You do not have this authority') {
                        if (data.url) {
                            setTimeout(function() {
                                location.href = data.url;
                            }, 1000);
                        }
                    }
                }, 'json');
            }
        });
    }

    exports('datashow', datashow); //对外接口
});